﻿using BacklogParser.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace BacklogParser.Parsers
{
    public static class InventorParser
    {
        public static List<Inventor> Parse(XElement parties)
        {
            var inventors = parties.Descendants(Constants.Epo + "inventors").ToList();
            return ParseInventors(inventors);
        }

        private static List<Inventor> ParseInventors(List<XElement> inventors)
        {
            var result = new List<Inventor>();
            foreach (var inventorElem in inventors)
            {
                var changeDateElem = inventorElem.Attribute("change-date");
                var changeGazetteElem = inventorElem.Attribute("change-gazette-num");
                string changeDate = "";
                string changeGazette = "";

                if (changeDateElem != null)
                    changeDate = changeDateElem.Value;

                if (changeGazetteElem != null)
                    changeGazette = changeGazetteElem.Value;

                var currentInventors = inventorElem.Descendants(Constants.Epo + "inventor").ToList();

                foreach (var item in currentInventors)
                {
                    var addres = item.Descendants(Constants.Epo + "addressbook").First();
                    var addressBook = AddressBookParser.Parse(addres);
                    var parsedInventor = Inventor.Create(addressBook);

                    var sequenceAttr = item.Attribute("sequence");

                    string sequence = "";
                    if (sequenceAttr != null) sequence = sequenceAttr.Value;


                    parsedInventor.ChangeDate = changeDate;
                    parsedInventor.ChangeGazette = changeGazette;
                    parsedInventor.Sequence = sequence;
                    

                    result.Add(parsedInventor);
                }
            }
            return result;
        }
    }
}
